package com.starhub.application.message.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.starhub.application.agent.enums.ChatMessageTypeEnum;
import com.starhub.application.message.dto.Message;
import com.starhub.common.bean.agent.AiFunction;

import dev.langchain4j.agent.tool.ToolSpecification;
import dev.langchain4j.data.message.*;
import dev.langchain4j.model.chat.request.json.JsonArraySchema;
import dev.langchain4j.model.chat.request.json.JsonObjectSchema;
import dev.langchain4j.model.chat.request.json.JsonStringSchema;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Objects;

@Slf4j
public class Utils {

    /*
     * 转换消息类型
     *
     * @param message 消息
     *
     * @return 转换后的消息
     */
    public static ChatMessage transMessage(Message message) {
        if(Objects.isNull(message) || StringUtils.isBlank(message.getRole())) {
            return null;
        }
        ChatMessageTypeEnum typeEnum =  ChatMessageTypeEnum.getByCode(message.getRole());
        if(Objects.isNull(typeEnum)) {
            return null;
        }
        ChatMessage chatMessage = null;
        switch (typeEnum) {
            case USER:
                chatMessage = UserMessage.from(message.getContent());
                break;
            case ASSISTANT:
                chatMessage = AiMessage.from(message.getContent());
                break;
            case SYSTEM:
                chatMessage = SystemMessage.from(message.getContent());
                break;
            case TOOL:
            case FUNCTION:
                chatMessage = ToolExecutionResultMessage.from(null, message.getCallFuncName(), message.getContent());
                break;
            default:
                log.warn("未知的消息类型: {}", message.getRole());
        }
        return chatMessage;
    }

    /**
     * 将AiFunction转换为ToolSpecification
     *
     * @param function AI函数
     * @return 工具规格
     */
    public static ToolSpecification convertToToolSpecification(AiFunction function) {
        JsonObjectSchema parameters = null;
        if (function.getParameters() != null && !function.getParameters().isEmpty()) {
            try {
                // 解析参数JSON
                JSONObject paramsJson = JSON.parseObject(function.getParameters());
                JsonObjectSchema.Builder builder = JsonObjectSchema.builder();

                // 处理属性
                if (paramsJson.containsKey("properties")) {
                    JSONObject properties = paramsJson.getJSONObject("properties");
                    for (String propertyName : properties.keySet()) {
                        JSONObject propertyConfig = properties.getJSONObject(propertyName);
                        String type = propertyConfig.getString("type");
                        String description = propertyConfig.getString("description");

                        // 根据类型添加不同的属性
                        switch (type.toLowerCase()) {
                            case "integer":
                                builder.addIntegerProperty(propertyName, description);
                                break;
                            case "number":
                                builder.addNumberProperty(propertyName, description);
                                break;
                            case "boolean":
                                builder.addBooleanProperty(propertyName, description);
                                break;
                            case "array":
                                // 对于数组类型，这里简化处理
                                builder.addProperty(propertyName, JsonArraySchema.builder()
                                                                                 .description(description)
                                                                                 .items(JsonStringSchema.builder().build())
                                                                                 .build());
                                break;
                            case "object":
                                // 对于对象类型，这里简化处理
                                builder.addProperty(propertyName, JsonObjectSchema.builder()
                                                                                  .description(description)
                                                                                  .build());
                                break;
                            default:
                                builder.addStringProperty(propertyName, description);
                        }
                    }
                }

                // 处理必填属性
                if (paramsJson.containsKey("required")) {
                    List<String> required = paramsJson.getJSONArray("required").toJavaList(String.class);
                    builder.required(required);
                }

                parameters = builder.build();
            } catch (Exception e) {
                log.error("解析函数参数失败", e);
                // 创建一个空的参数结构
                parameters = JsonObjectSchema.builder().build();
            }
        } else {
            parameters = JsonObjectSchema.builder().build();
        }

        return ToolSpecification.builder()
                                .name(function.getName())
                                .description(function.getDescription())
                                .parameters(parameters)
                                .build();
    }
}
